<?php

// +----------------------------------------------------------------------
// | Shop-Demo for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2022~2023 Anyon <zoujingli@qq.com>
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// | 会员免费 ( https://thinkadmin.top/vip-introduce )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\data\controller\user;

use app\data\model\DataQiyeBiaoqian;
use app\data\model\DataQiyeBiaoqian as DataNewsItem;
use app\data\model\DataQiyeRzinfo;
use app\data\model\DataQiyeXinxiku;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\facade\Request;

/**
 * 企业标签
 * Class Item
 * @package app\data\controller\news
 */
class Qiyebiaoqian extends Controller
{
    /**
     * 企业标签管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->type = $this->get['type'] ?? 'index';
        DataNewsItem::mQuery($this->get)->layTable(function ()
        {
            $this->title = '企业标签';
        }, function (QueryHelper $query)
        {
            $query->like('name')->dateBetween('create_at');
            $query->where(['status' => intval($this->type === 'index'), 'deleted' => 0]);
        });
    }

    /**
     * 列表数据处理
     * @param  array  $data
     */
    protected function _page_filter(array &$data)
    {

        foreach ($data as &$item) {

            if ($item['is_kj'] == 1) {
                $item['is_kj_txt'] = '可见';
            } else {
                $item['is_kj_txt'] = '不可见';
            }

        }


    }

    /**
     * 添加企业标签
     * @auth true
     */
    public function add()
    {
        $this->title = '添加内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 编辑企业标签
     * @auth true
     */
    public function edit()
    {
        $this->title = '编辑内容';
        DataNewsItem::mForm('form');
    }

    protected function _add_form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            $data['id'] = 0;
        }
    }

    protected function _edit_form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            $enterpriseList    = DataQiyeXinxiku::whereFindInSet('qybq', $data['id'])
                ->select()->toArray();
            $this->enterprises = implode(',', array_column($enterpriseList, 'id'));
        }
    }

    /**
     * 表单数据处理
     * @param  array  $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if (empty($data['code'])) {

        }
        if ($this->request->isGet()) {

        } else {

        }
    }

    /**
     * 表单结果处理
     * @param  boolean  $state
     * @param           $data
     */
    protected function _form_result(bool $state, $data)
    {
        if ($state) {
            $id                  = $data['id'];
            $enterpriseList      = DataQiyeXinxiku::whereFindInSet('qybq', $id)
                ->select()->toArray();
            $reqEnterpriseIds    = explode(',', $data['enterprises']);
            $selectEnterpriseIds = array_column($enterpriseList, 'id');
            if ($reqEnterpriseIds == $selectEnterpriseIds) {
                $this->success('保存成功！', 'javascript:history.back()');
            }

            if ($delArr = array_diff($selectEnterpriseIds, $reqEnterpriseIds)) {
                //处理需要删除当前企业标签的企业
                DataQiyeXinxiku::whereIn('id', $delArr)->select()->each(function ($item) use ($id)
                {
                    /**
                     * @var $item DataQiyeXinxiku
                     */
                    $ids = explode(',', $item->qybq);
                    $ids = array_diff($ids, [$id]);
                    $tag = implode(',', $ids);
                    $item->save(['qybq' => $tag]);
                    //更新企业认证信息
                    if ($enterpriseCertify = DataQiyeRzinfo::where('qrxxk_id', $item->getKey())->select()) {
                        $enterpriseCertify->each(function ($item) use ($tag)
                        {
                            $item->save(['qybq' => $tag]);
                        });
                    }
                });
            }
            if ($addArr = array_diff($reqEnterpriseIds, $selectEnterpriseIds)) {
                //处理需要新增当前企业标签的企业
                DataQiyeXinxiku::whereIn('id', $addArr)->select()->each(function ($item) use ($id)
                {
                    /**
                     * @var $item DataQiyeXinxiku
                     */
                    $ids   = explode(',', $item->qybq);
                    $ids[] = $id;
                    $tag   = implode(',', $ids);
                    $item->save(['qybq' => $tag]);
                    //同步企业认证信息
                    if ($enterpriseCertify = DataQiyeRzinfo::where('qrxxk_id', $item->getKey())->select()) {
                        $enterpriseCertify->each(function ($item) use ($tag)
                        {
                            $item->save(['qybq' => $tag]);
                        });
                    }
                });
            }
            $this->success('保存成功！', 'javascript:history.back()');
        }
    }

    /**
     * 修改状态
     * @auth true
     */
    public function state()
    {
        DataNewsItem::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除企业标签
     * @auth true
     */
    public function remove()
    {
        DataNewsItem::mDelete();
    }

    /**
     * 文章内容选择
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $this->get['status'] = 1;
        $this->index();
    }

    /**
     * 获取所有企业列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEnterpriseList()
    {
        $tags           = $this->request->get('tag');
        $enterpriseList = DataQiyeXinxiku::query()->where('status', 1);
        if ($tags = $tags ? explode(',', $tags) : null) {
            $row = '(';
            foreach ($tags as $tag) {
                $row .= "find_in_set('{$tag}',qybq) or ";
            }
            $row            = rtrim($row, 'or ');
            $row            .= ')';
            $enterpriseList = $enterpriseList->whereRaw($row);
        }
        $enterpriseList = $enterpriseList->select();

        return_msg(200, 'success', $enterpriseList);
    }

    /**
     * 数据导入
     */
    public function import()
    {
        $data  = $this->request->all();
        $tagId = $data['id'] ?? '';

        if (!$tagId) {
            return_error('参数错误');
        }
        //查询标签是否存在
        /**
         * @var $tag DataQiyeBiaoqian
         */
        $tag = DataQiyeBiaoqian::query()->where('id', $tagId)->find();
        if (!$tag) {
            return_error('标签不存在');
        }
        //获取文件
        $file = $this->app->request->post('file');
        $file = '.' . str_replace($this->app->request->domain(), '', $file);
        //表格字段对应
        $cellName = [
            'A' => 'qymc',  //企业名称
            'B' => 'tyxydm',//统一信用代码
        ];
        //加载文件
        $spreadsheet = IOFactory::load($file);

        $sheet      = $spreadsheet->getActiveSheet();               // 获取表格
        $highestRow = $sheet->getHighestRow();                      // 取得总行数
        $sheetData  = [];
        // 批量修改信息库现有数据
        DataQiyeXinxiku::query()->whereFindInSet('qybq', $tagId)->select()->each(function ($item) use ($tagId)
        {
            $tag    = $item->qybq;
            $parts  = explode(',', $tag);
            $parts  = array_filter($parts, function ($part) use ($tagId)
            {
                return $part !== $tagId;
            });
            $newTag = implode(',', $parts);
            $item->save(['tag' => $newTag]);
        });

        //读取数据
        for ($row = 2; $row <= $highestRow; $row++) {          // $row表示从第几行开始读取
            foreach ($cellName as $cell => $field) {
                $code       = trim($sheet->getCell($cell . $row)->getValue());
                $enterprise = DataQiyeXinxiku::query()->where('tyxydm', $code)->find();
                if ($enterprise) {
                    $enterprise->save(['qybq' => $enterprise->qybq . ',' . $tagId]);
                }
            }
        }
        $this->success('导入成功');
    }

    public function upload()
    {
        // 获取上传文件
        $file = Request::file('file');

        if ($file->getMime() != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            $this->error('文件格式不正确');
        }
        $filePath = $file->move('upload/' . date('Ymd'), $file->getOriginalName());
        $this->success('文件上传成功', ['url' => $this->app->request->domain() . '/' . $filePath->getPath() . '/' . $filePath->getFilename()]);
    }
}
